package leetcode.动态规划和贪心;

/**
 * 最大子序和
 */
public class Test53最大子序和 {

    /**
     * 贪心法：一旦遇到 sum 小于 0 的情况立刻寻找新的子数组
     * <p>
     * 不需要管最大和的数组是什么，只需要知道最大和是什么即可
     * <p>
     * 遍历数组，累加，当累加的值小于0时，从下一元素开始再重新累加。
     * 在这个过程中记录下最大的累加值就可以了。
     */
    public static int maxSubArray(int[] nums) {
        int res = nums[0];
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (max < 0) {
                max = nums[i];
            } else {
                max += nums[i];
            }
            res = Math.max(max, res);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(a));
        System.out.println(maxSubArray2(a));
    }

    /**
     * 分治法：把原数组从中间一分为二，然后递归地去处理左右子数组
     */
    public static int maxSubArray2(int[] nums) {
        int result = maxSubArrayHelper(nums, 0, nums.length - 1);
        return result;
    }

    private static int maxSubArrayHelper(int[] nums, int left, int right) {
        if (left == right)
            return nums[left];

        int mid = (left + right) / 2;
        int leftMax = maxSubArrayHelper(nums, left, mid);
        int rightMax = maxSubArrayHelper(nums, mid + 1, right);
        int crossLineMax = crossLineHelper(nums, left, right, mid);
        return Math.max(Math.max(leftMax, rightMax), crossLineMax);
    }

    private static int crossLineHelper(int[] nums, int left, int right, int mid) {

        if (left == right)
            return nums[left];

        int tmpSum = 0;
        int leftSum = Integer.MIN_VALUE;

        for (int i = mid; i >= left; i--) {
            tmpSum += nums[i];
            leftSum = Math.max(tmpSum, leftSum);
        }

        int rightSum = Integer.MIN_VALUE;
        tmpSum = 0;

        for (int i = mid + 1; i <= right; i++) {
            tmpSum += nums[i];
            rightSum = Math.max(tmpSum, rightSum);
        }

        return leftSum + rightSum;
    }
}
